#include "recbox.h"
#include "ui_recbox.h"
#include"recboxitem.h"
#include<QJsonObject>

RecBox::RecBox(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RecBox)
    , _row(1)
    , _col(4)
{
    ui->setupUi(this);
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data, int row)
{
    if(row == 2){
        _row = row;
        _col = 8;
    }
    else{
        //隐藏RecBoxDownHlyout
        ui->recListDown->hide();
    }
    _imageList = data;

    //当前在第几组，默认0组
    _currentIndex = 0;
    _count = ceil(data.size() / _col); //算出有多少组

    createRecBoxItem();
}

void RecBox::createRecBoxItem()
{
    //移除之前存在的旧元素
    QList<RecBoxItem*> recUpList = ui->recListUp->findChildren<RecBoxItem*>();
    for(auto e : recUpList){
        ui->recListUpHLayout->removeWidget(e);
        delete e;
    }

    QList<RecBoxItem*> recDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for(auto e : recDownList){
        ui->recListDownHLayout->removeWidget(e);
        delete e;
    }

    int index = 0;
    for(int i = _currentIndex * _col; i < _col + _currentIndex * _col; ++i){
        RecBoxItem* item = new RecBoxItem();
        QJsonObject obj = _imageList[i].toObject();
        item->setText(obj.value("text").toString());
        item->setImage(obj.value("imagePath").toString());



        if(index >= _col / 2 && _row == 2){
            ui->recListDownHLayout->addWidget(item);
        }
        else{
            ui->recListUpHLayout->addWidget(item);
        }
        ++index;
    }
}

void RecBox::on_btUp_clicked()
{
    _currentIndex--;
    if(_currentIndex < 0)_currentIndex = 0;

    createRecBoxItem();
}


void RecBox::on_btDown_clicked()
{
    _currentIndex++;
    if(_currentIndex == _count)_currentIndex = 0;

    createRecBoxItem();
}
